package org.abacus.platform.database.impl;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.abacus.platform.data.ConnectionProvider;

public class DataSourceProvider implements DataSource, ConnectionProvider {
	private String url = "jdbc:mysql://127.0.0.1:3306/abacus?useUnicode=true&amp;characterEncoding=UTF-8&amp;mysqlEncoding=utf-8";
	private String username = "root";
	private String password = "root";
	private int loginTimeout = 3000;
	private PrintWriter out;
	private String driverClassName = "com.mysql.jdbc.Driver";

	public PrintWriter getLogWriter() throws SQLException {
		if (null == out) {
			out = new PrintWriter(System.out);
		}
		return out;
	}

	public void setLogWriter(PrintWriter out) throws SQLException {
		this.out = out;
	}

	public void setLoginTimeout(int seconds) throws SQLException {
		loginTimeout = seconds;
	}

	public int getLoginTimeout() throws SQLException {
		return loginTimeout;
	}

	public <T> T unwrap(Class<T> iface) throws SQLException {
		throw new SQLException("not support");
	}

	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		throw new SQLException("not support");
	}

	public Connection getConnection() throws SQLException {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return DriverManager.getConnection(url, username, password);
	}

	public Connection getConnection(String username, String password) throws SQLException {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return DriverManager.getConnection(url, username, password);
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getDriverClassName() {
		return driverClassName;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	@Override
	public void close(Connection conn) {
		try {
			if (null != conn && !conn.isClosed()) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void close() {

	}
}
